<template>
	<view class="home">
    <u-picker v-model="show" mode="time"></u-picker>
    <u-button @click="show = true">打开</u-button>
<!-- #ifndef MP-WEIXIN -->
    <view class="purple_btn btn_box" @click="savePoster">
        保存到相册1
    </view>
    <!-- #endif -->
    
    <!-- #ifdef MP-WEIXIN -->
    <view v-if="openSettingBtnHidden" class="purple_btn btn_box" @click="saveEwm">
        微信小程序保存到相册成功2
    </view>
    <view v-if="openSettingBtnHidden" class="purple_btn btn_box" @click="savePoster">
      微信小程序保存到相册打不开3
    </view>
    <button v-else class="purple_btn btn_box" hover-class="none" open-type="openSetting" @opensetting='savePoster'>保存到相册3</button>
    <!-- #endif -->



		 <swiper class="swiper" indicator-dots="true" autoplay="true" interval="5000" duration="500">
			<swiper-item v-for="item in swipers" :key='item.goods_id'>
				<img :src='item.image_src'/>
			</swiper-item>
		</swiper>
		<view class="nav">
			<view class="nav_item" v-for="(item,index) in navs" :key="index" @click="navItemClick(item.path)">
				<view :class="item.icon"></view>
				<text>{{item.title}}</text>
			</view>
		</view>
		<!-- 分享功能 -->
		<button data-name="shareBtn" @click="shareFriend" open-type="share">分享给朋友</button>
<!--		<button data-name="shareBtn" @click="shareFriendcricle" open-type="share">分享到朋友圈</button>-->
<!--    <video id="myVideo" src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" @click="playvideo" @fullscreenchange="fullscreenchange"></video>-->
    <view class="other_cont">
<!--      <scroll-view scroll-x="true" class="other_scr">-->
<!--        <template v-for="(item, index) in planData">-->
<!--          <view class="other_item" v-if="index < 5" :key="index">-->
<!--            <view class="z-index" @click="videoshow(item)"></view>-->
<!--            <video :src="item" controls="false"></video>-->
<!--          </view>-->
<!--        </template>-->
<!--      </scroll-view>-->
<!--    </view>-->
      <button  @click="videoshow">全屏</button>

      <video  controls @play="videoPlay('myvideo')"
              id="myvideo" :show-fullscreen-btn="false"
             src= "http://vjs.zencdn.net/v/oceans.mp4" controls="true"></video>
    </view>

    <button data-name="shareBtn" @click="upload">上传</button>
    <!-- 推荐商品 -->
		<view class="hot_goods">
			<view class="tit">推荐商品</view>
			<goods-list @goodsItemClick="goGoodsDetail" :goods="goods"></goods-list>
			
		</view>
	</view>
</template>

<script>
	import goodsList from '../../common/goods-list/goods-list.vue'
  import jietu from "./jietu";
  var _self;
	export default {
		components:{goodsList,jietu},
		data() {
			return {
        show: false,
        url: 'https://img13.360buyimg.com/n5/jfs/t15574/103/2503735642/354259/239cea20/5aaf4e5cN7ed2aacd.jpg',//图片地址
        // url: '/static/img/share.png',//图片地址

        videoId:null,
				openSettingBtnHidden: true,//是否授权
				            ewmImg:"",//这是要保存的图片
        playerOptions: {
          playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
          autoplay: false, //如果true,浏览器准备好时开始回放。
          muted: false, // 默认情况下将会消除任何音频。
          loop: false, // 导致视频一结束就重新开始。
          preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: "zh-CN",
          aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          sources: [
            {
              // src: "//path/to/video.mp4", // 路径
              src: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4", // 路径
              type: "video/mp4" // 类型
            }
          ],
          // poster: "../../static/images/test.jpg", //你的封面地址
          // poster: "https://vdposter.bdstatic.com/b6d6bd184e72a1567e3c8ee8d1b8ffd1.jpeg?x-bce-process=image/resize,m_fill,w_320,h_180/format,f_jpg/quality,Q_100", //你的封面地址
          // width: document.documentElement.clientWidth,
          notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
          controlBar: {
            timeDivider: true,
            durationDisplay: true,
            remainingTimeDisplay: false,
            fullscreenToggle: true //全屏按钮
          }
      },
        planData:[
          "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",
          "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",
          "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
        ],
        videoUrl: "", //全屏播放视频的URL
				title: '首页',
				swipers:[],
				goods: [],
				navs: [
					{
						icon: 'iconfont icon-ziyuan',
						title: '大炮超市',
						path: '/pages/goods/goods'
					},
					{
						icon: 'iconfont icon-guanyuwomen',
						title: '联系我们',
						path: '/pages/contact/contact'
					},
					{
						icon: 'iconfont icon-tupian',
						title: '社区图片',
						path: '/pages/pics/pics'
					},
					{
						icon: 'iconfont icon-shipin',
						title: '学习视频',
						path: '/pages/videos/videos'
					}
				]
			}
		},
		onLoad(opt) {
			   _self = this;
      if (opt.source === "c") {
        uni.navigateTo({
          url: '/pages/goods/goods'
        }) //参数拼接在后面即可

      }
        this.getSwiper()
			this.getHotGoods()
		},
    // 这里myvideo 是你上面命名的id
    onReady: function () {
      this.videoContext = uni.createVideoContext("myvideo", this);    // this这个是实例对象  必传
    },

		methods: {
			//微信小程序保存到相册
			        saveEwm:function(e){
			            //获取相册授权
			               uni.getSetting({
			                 success(res) {
			                   if (!res.authSetting['scope.writePhotosAlbum']) {
			                     uni.authorize({
			                       scope: 'scope.writePhotosAlbum',
			                       success() {
			                         //这里是用户同意授权后的回调
			                         _self.saveImgToLocal();
			                       },
			                       fail() {//这里是用户拒绝授权后的回调
			                           _self.openSettingBtnHidden=false
			                       }
			                     })
			                   } else {//用户已经授权过了
			                     _self.saveImgToLocal();
			                   }
			                 }
			               })
			        },
			        saveImgToLocal:function(e){
			            
			            uni.showModal({
			                title: '提示',
			                content: '确定保存到相册吗',
			                success: function (res) {
			                    if (res.confirm) {
			                        
			                        uni.downloadFile({
			                                url: _self.url,//图片地址
			                                success: (res) =>{
			                                    if (res.statusCode === 200){
			                                        uni.saveImageToPhotosAlbum({
			                                            filePath: res.tempFilePath,
			                                            success: function() {
			                                                uni.showToast({
			                                                    title: "保存成功",
			                                                    icon: "none"
			                                                });
			                                            },
			                                            fail: function() {
			                                                uni.showToast({
			                                                    title: "保存失败",
			                                                    icon: "none"
			                                                });
			                                            }
			                                        });
			                                    } 
			                                }
			                            })
			                        
			                        
			                    } else if (res.cancel) {
			                        
			                    }
			                }
			            });
						},

      savePoster() {
        uni.getSetting({ //获取用户的当前设置
          success: (res) => {
            if (res.authSetting['scope.writePhotosAlbum']) { //验证用户是否授权可以访问相册
              this.saveImageToPhotosAlbum();
            } else {
              uni.authorize({ //如果没有授权，向用户发起请求
                scope: 'scope.writePhotosAlbum',
                success: () => {
                  this.saveImageToPhotosAlbum();
                },
                fail: () => {
                  uni.showToast({
                    title: "请打开保存相册权限，再点击保存相册分享",
                    icon: "none",
                    duration: 3000
                  });
                  setTimeout(() => {
                    uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
                      success: (res2) => {
                        // console.log(res2.authSetting)
                      }
                    });
                  }, 3000);
                }
              })
            }
          }
        })
      },
      saveImageToPhotosAlbum() {
        let base64 = this.url.replace(/^data:image\/\w+;base64,/, ""); //去掉data:image/png;base64,
        let filePath = wx.env.USER_DATA_PATH + '/ph_fit_qrcode.png';
        uni.showLoading({
          title: '加载中',
          mask: true
        })
        uni.getFileSystemManager().writeFile({
          filePath: filePath, //创建一个临时文件名
          data: base64, //写入的文本或二进制数据
          encoding: 'base64', //写入当前文件的字符编码
          success: res => {
            uni.saveImageToPhotosAlbum({
              filePath: filePath,
              success: function(res2) {
                uni.hideLoading();
                uni.showToast({
                  title: '保存成功，请从相册选择再分享',
                  icon: "none",
                  duration: 5000
                })
              },
              fail: function(err) {
                uni.hideLoading();
                // console.log(err.errMsg);
              }
            })
          },
          fail: err => {
            uni.hideLoading();
            //console.log(err)
          }
        })
      },
      // 视频播放
      videoPlay(id){
        // 解决真机无限播放暂停问题
        if(this.videoId==id){
          return false
        }
        this.videoId=id
        this.videoContext = uni.createVideoContext("myvideo", this);
        this.videoContext.play()

      },
      playVieo(){
        this.videoContext.play();
      },
      stopVideo(){
        this.videoContext.pause();
      },
      videoshow(e) {
        this.videoContext.requestFullScreen({ direction: 90 });
        this.videoContext.showStatusBar();
      },
			upload(){
				// uni.navigateBack(); 
				// this.$router.go(0)
				// this.location.reload()
				uni.chooseImage({
			    success: (chooseImageRes) => {
			        const tempFilePaths = chooseImageRes.tempFilePaths;
			        uni.uploadFile({
			            url: 'https://www.example.com/upload', //仅为示例，非真实的接口地址
			            filePath: tempFilePaths[0],
			            name: 'file',
			            formData: {
			                'user': 'test'
			            },
			            success: (uploadFileRes) => {
			                console.log(uploadFileRes.data);
			            }
			        });
			    }
			});
			},


			// 获取轮播图的数据
			async getSwiper(){
				const res = await this.http({url:'/api/public/v1/home/swiperdata'})
				this.swipers = res.data.message;
			},
			// 获取热门商品列表数据
			async getHotGoods () {
				const res = await this.http({
					url: '/api/public/v1/goods/search?pagenum=1'
				})
				this.goods = res.data.message.goods
				console.log(this.goods)
			},
			// 导航点击的处理函数
			navItemClick (url) {
				console.log(url)
				uni.navigateTo({
					url
				})
			},
			// 导航到商品详情页
			goGoodsDetail (id) {
				uni.navigateTo({
					url: '../goodsDetail/goodsDetail?goods_id='+id
				})
			}
		}
	}
</script>

<style lang="scss">
	.home{
		swiper{
			width: 750rpx;
			height: 380rpx;
			image{
				height: 100%;
				width: 100%;
			}
		}
		.nav {
			display: flex;
			.nav_item {
				width: 25%;
				text-align: center;
				view{
					width: 120rpx;
					height: 120rpx;
					background: $shop-color;
					border-radius: 60rpx;
					margin: 10px auto;
					line-height: 120rpx;
					color: #fff;
					font-size: 50rpx;
				}
				.icon-tupian{
					font-size: 45rpx;
				}
				text{
					font-size: 30rpx;
				}
			}
		}
		.hot_goods {
			background: #eee;
			overflow: hidden;
			margin-top: 10px;
			.tit{
				height: 50px;
				line-height: 50px;
				color: $shop-color;
				text-align: center;
				letter-spacing: 20px;
				background: #fff;
				margin: 7rpx 0;
			}
		}
		
	}
</style>
